package com.thunder.ktv.scoreengine2test.ui;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

// 假设 ScoreEngine2.ScoreResult 在这里可以被访问到
 import com.thunder.ktv.scoreengine2sdk.ScoreEngine2;

 import java.util.Arrays;
 import java.util.Locale;

 public class ScoreRadarChartView extends View {

     private static final String TAG = "ScoreRadarChartView";

     // --- 配置 ---
     private static final int DIMENSION_COUNT = 5;
     private static final int LAYER_COUNT = 4;
     private final String[] mDimensionLabels = {"音高", "情感", "节奏", "气息", "亮度"};
     // 【新】默认每个维度的满分就是100
     private static final int MAX_SCORE_PER_DIMENSION = 100;

     // --- 数据 ---
     private final long[] mCumulativeScores = new long[DIMENSION_COUNT];
     private int mCallCount = 0;
     private int mOverallScore = 0;

     // --- 绘图 ---
     private Paint mGridPaint, mLabelPaint, mScoreFillPaint, mScoreStrokePaint, mCenterTextPaint;
     private Path mScorePath;
     private float mRadius, mCenterX, mCenterY;
     private final float mAngle = (float) (2 * Math.PI / DIMENSION_COUNT);
     private final float mStartAngle = (float) (-Math.PI / 2);

     public ScoreRadarChartView(Context context) { super(context); init(); }
     public ScoreRadarChartView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); }
     public ScoreRadarChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); }

     private void init() {
         mGridPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
         mGridPaint.setColor(Color.parseColor("#66FFFFFF"));
         mGridPaint.setStyle(Paint.Style.STROKE);

         mLabelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
         mLabelPaint.setColor(Color.WHITE);
         mLabelPaint.setStyle(Paint.Style.FILL);

         mScoreFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
         mScoreFillPaint.setColor(Color.parseColor("#8000BFFF"));
         mScoreFillPaint.setStyle(Paint.Style.FILL);

         mScoreStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
         mScoreStrokePaint.setColor(Color.parseColor("#FF00BFFF"));
         mScoreStrokePaint.setStyle(Paint.Style.STROKE);

         mCenterTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
         mCenterTextPaint.setColor(Color.YELLOW);
         mCenterTextPaint.setStyle(Paint.Style.FILL_AND_STROKE);
         mCenterTextPaint.setTextAlign(Paint.Align.CENTER);

         mScorePath = new Path();
     }

     @Override
     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
         super.onSizeChanged(w, h, oldw, oldh);
         mCenterX = w / 2f;
         mCenterY = h / 2f;
         mRadius = Math.min(w, h) / 2f * 0.7f;
         mGridPaint.setStrokeWidth(mRadius / 120f);
         mLabelPaint.setTextSize(mRadius / 9f);
         mScoreStrokePaint.setStrokeWidth(mRadius / 60f);
         mCenterTextPaint.setTextSize(mRadius / 2.5f);
         mCenterTextPaint.setStrokeWidth(mRadius / 80f);
     }

     @Override
     protected void onDraw(Canvas canvas) {
         super.onDraw(canvas);
         drawGrid(canvas);
         drawLabels(canvas);
         drawScorePolygon(canvas);
         drawCenterScore(canvas);
     }

     private void drawScorePolygon(Canvas canvas) {
         if (mCallCount == 0) {
             return;
         }
         mScorePath.reset();
         for (int i = 0; i < DIMENSION_COUNT; i++) {
             // 1. 计算平均分
             float averageScore = (float) mCumulativeScores[i] / mCallCount;

             // 2. 计算平均分在0-100范围内的比例
             float ratio = averageScore / MAX_SCORE_PER_DIMENSION;
             ratio = Math.max(0f, Math.min(1f, ratio)); // 保证比例在0-1之间

             // 打印调试信息，确认计算正确
             Log.v(TAG, String.format(Locale.US,
                     "Drawing Dim %d (%s): avgScore=%.2f, ratio=%.2f",
                     i, mDimensionLabels[i], averageScore, ratio));

             float x = (float) (mCenterX + mRadius * ratio * Math.cos(mStartAngle + mAngle * i));
             float y = (float) (mCenterY + mRadius * ratio * Math.sin(mStartAngle + mAngle * i));

             if (i == 0) {
                 mScorePath.moveTo(x, y);
             } else {
                 mScorePath.lineTo(x, y);
             }
         }
         mScorePath.close();

         canvas.drawPath(mScorePath, mScoreFillPaint);
         canvas.drawPath(mScorePath, mScoreStrokePaint);
     }


     // --- Public API ---

     /**
      * 【新】重置所有分数和状态，用于开始新一轮计分。
      */
     public void reset() {
         Log.d(TAG, "===== reset() called, clearing all scores. =====");
         mCallCount = 0;
         mOverallScore = 0;
         Arrays.fill(mCumulativeScores, 0);
         postInvalidate(); // 重绘以清空雷达图
     }

     /**
      * 【新】添加单句分数。
      * 内部会累加分数并计算平均值来更新雷达图。
      * @param result 包含本次单句分数的对象 (pitchScore等应在0-100之间)
      */
     public void addScore(ScoreEngine2.ScoreResult result) {
         if (result == null || !result.isValid()) {
             Log.w(TAG, "addScore received invalid result. Ignoring.");
             return;
         }

         Log.d(TAG, "--- addScore called (call #" + (mCallCount + 1) + ") ---");
         Log.d(TAG, "Incoming scores: pitch=" + result.pitchScore + ", emotion=" + result.emotionScore +
                 ", rhythm=" + result.rhythmScore + ", breath=" + result.breathScore + ", brightness=" + result.brightnessScore);

         mCallCount++;

         // 累加每个维度的分数
         mCumulativeScores[0] += result.pitchScore;
         mCumulativeScores[1] += result.emotionScore;
         mCumulativeScores[2] += result.rhythmScore;
         mCumulativeScores[3] += result.breathScore;
         mCumulativeScores[4] += result.brightnessScore;

         // SDK给的overallScore通常是累加后的总分，所以直接赋值
         mOverallScore = result.overallScore;

         Log.d(TAG, "Cumulative scores: " + Arrays.toString(mCumulativeScores));
         Log.d(TAG, "Overall score updated to: " + mOverallScore);

         postInvalidate(); // 请求重绘
     }


     // --- 未修改的辅助绘图方法 ---

     private void drawGrid(Canvas canvas) {
         Path path = new Path();
         float r = mRadius / LAYER_COUNT;
         for (int i = 1; i <= LAYER_COUNT; i++) {
             float currentRadius = r * i;
             path.reset();
             for (int j = 0; j < DIMENSION_COUNT; j++) {
                 float x = (float) (mCenterX + currentRadius * Math.cos(mStartAngle + mAngle * j));
                 float y = (float) (mCenterY + currentRadius * Math.sin(mStartAngle + mAngle * j));
                 if (j == 0) path.moveTo(x, y); else path.lineTo(x, y);
             }
             path.close();
             canvas.drawPath(path, mGridPaint);
         }
         for (int i = 0; i < DIMENSION_COUNT; i++) {
             float x = (float) (mCenterX + mRadius * Math.cos(mStartAngle + mAngle * i));
             float y = (float) (mCenterY + mRadius * Math.sin(mStartAngle + mAngle * i));
             canvas.drawLine(mCenterX, mCenterY, x, y, mGridPaint);
         }
     }

     private void drawLabels(Canvas canvas) {
         for (int i = 0; i < DIMENSION_COUNT; i++) {
             float currentAngle = mStartAngle + mAngle * i;
             float labelRadius = mRadius * 1.05f;
             float x = (float) (mCenterX + labelRadius * Math.cos(currentAngle));
             float y = (float) (mCenterY + labelRadius * Math.sin(currentAngle));
             String label = mDimensionLabels[i];
             float angleDeg = (float) Math.toDegrees(currentAngle % (2 * Math.PI));
             if (angleDeg < 0) angleDeg += 360;
             if (Math.abs(angleDeg - 90) < 5 || Math.abs(angleDeg - 270) < 5) mLabelPaint.setTextAlign(Paint.Align.CENTER);
             else if (angleDeg > 90 && angleDeg < 270) mLabelPaint.setTextAlign(Paint.Align.RIGHT);
             else mLabelPaint.setTextAlign(Paint.Align.LEFT);
             Paint.FontMetrics fontMetrics = mLabelPaint.getFontMetrics();
             float textCenterY = y + (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
             canvas.drawText(label, x, textCenterY, mLabelPaint);
         }
     }

     private void drawCenterScore(Canvas canvas) {
         Paint.FontMetrics fontMetrics = mCenterTextPaint.getFontMetrics();
         float distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
         float baseline = mCenterY + distance;
         canvas.drawText(String.valueOf(mOverallScore), mCenterX, baseline, mCenterTextPaint);
     }
 }

